/**
 * @file api.js
 * @author zhangxueqiong
 * @date 2022/08/09
 */
import URL from 'url-parse';
import { postRequest, getRequest } from './request';
import i18n from '@/locale';
import store from '@/store';

// 测试token，具体的token方法后续补充
/* eslint-disable max-len */
// const ACCESS_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiNDk1NDUyZjcyOWRjNDQ4NmFlNTc0YjI1ZGI1YTM4ZjQiLCJ1c2VyX2luZm8iOiJ7XCJpZFwiOlwiNDk1NDUyZjcyOWRjNDQ4NmFlNTc0YjI1ZGI1YTM4ZjRcIixcImxvZ2luTmFtZVwiOlwiYWRtaW5cIixcInVzZXJOYW1lXCI6XCJhZG1pblwiLFwidXNlclR5cGVcIjpcIjEwXCIsXCJuZWVkUHVzaFwiOjEsXCJsYW5ndWFnZVwiOlwiemhfQ05cIixcImRlcHRJZFwiOlwiNDM2OTkwNjI0NDA4MDE4OTQ0XCIsXCJwaG9uZVwiOlwiYWRtaW5cIn0iLCJpc3MiOiJTZXJ2aWNlIiwiZXhwIjoxNjYxNjY3NDk3LCJpYXQiOjE2NjA4MDM0OTd9.2p2NMORV9toLqmdiQUAKSfWPu-E-q-SzxQi3MJeu3OM';
// 公共超时时间3s
const TIMEOUT = 3000;

/**
 * 获取完整的请求url
 *
 * @param {endpoint} url 接口路径
 * @return {string} 返回完整的接口url
 */

const getFullUrl = (endpoint: any) => {
  // todo：如果是MOCK为true，也即本地开发时，需要把apiRoot设置为/request.ajax?path=，
  // 这是受限于mockservice这个模块的限制，后续要优化这个限制
  const apiRoot = process.env.MOCK
    ? '/request.ajax?path='
    : process.env.STAGE === 'test'
    ? 'http://101.200.196.223:8086/'
    : '/';
  const url = new URL(`${apiRoot}${endpoint}`);
  return url.toString();
};

const getRequestOptions = ({ path }: any) => {
  // // 处理请求公共数据
  // const formData = {
  //   params: JSON.stringify(params || {}),
  // };
  const fullUrl = getFullUrl(path);
  return {
    fullUrl,
    // formData,
  };
};

// 获取请求公共头部
const getRequestHeader = () => ({
  ACCESS_TOKEN: (store.state as any).user.token || '',
  'Client-Locale': i18n.global.locale.value || 'en-US',
  'System-Type': 'LEGAL',
  'Client-Type': 'WEB',
});

export const postApi = (path: any, params?: any, options?: any) => {
  const requestOptions = getRequestOptions({ path });
  const { fullUrl } = requestOptions;
  return postRequest(fullUrl, params, {
    timeout: TIMEOUT,
    headers: getRequestHeader(),
    ...options,
  }).then(
    (response: any) => response,
    (error: any) => {
      throw error;
    },
  );
};

export const getApi = (path: any, params?: any) => {
  const requestOptions = getRequestOptions({ path });
  const { fullUrl } = requestOptions;
  return getRequest(fullUrl, params, {
    timeout: TIMEOUT,
    headers: getRequestHeader(),
  }).then(
    (response: any) => response,
    (error: any) => {
      throw error;
    },
  );
};
